import cv2
from pyzbar import pyzbar
from datetime import datetime

def detect_barcodes(frame):
    detected_barcodes = []
    
    # 转换为灰度图
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
    # 识别条形码
    barcodes = pyzbar.decode(gray)
    
    for barcode in barcodes:
        (x, y, w, h) = barcode.rect
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        
        barcode_data = barcode.data.decode("utf-8")
        barcode_type = barcode.type
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        text = f"{barcode_data} ({barcode_type})"
        cv2.putText(frame, text, (x, y - 10), 
                   cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        
        detected_barcodes.append({
            "data": barcode_data,
            "type": barcode_type,
            "time": current_time
        })
    
    return frame, detected_barcodes

def main():
    # 视频文件路径
    video_path = "barcodes.mp4"  # 替换为你的视频文件路径
    cap = cv2.VideoCapture(video_path)
    
    if not cap.isOpened():
        print(f"无法打开视频文件: {video_path}")
        return
    
    # 性能优化参数
    skip_frames = 5  # 跳帧处理，每n帧处理一次
    resize_scale = 0.7  # 缩放比例，降低分辨率
    
    recognized_barcodes = set()
    frame_count = 0
    
    while True:
        ret, frame = cap.read()
        if not ret:
            break  # 视频结束
        
        frame_count += 1
        
        # 跳帧处理 - 只处理指定间隔的帧
        if frame_count % skip_frames != 0:
            # 仍然显示帧但不处理，保持播放流畅
            cv2.imshow("Barcode Scanner", frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
            continue
        
        # 降低分辨率以提高处理速度
        if resize_scale != 1.0:
            frame = cv2.resize(frame, (0, 0), fx=resize_scale, fy=resize_scale)
        
        # 识别条形码
        frame, detected_barcodes = detect_barcodes(frame)
        
        # 处理识别结果
        for barcode in detected_barcodes:
            if barcode["data"] not in recognized_barcodes:
                recognized_barcodes.add(barcode["data"])
                print(f"时间: {barcode['time']} 识别到: {barcode['data']} (类型: {barcode['type']})")
        
        # 显示处理后的帧
        cv2.imshow("Barcode Scanner", frame)
        
        # 按键控制
        key = cv2.waitKey(1) & 0xFF
        if key == ord('q'):
            break
        elif key == ord('+') and skip_frames > 1:
            skip_frames -= 1  # 减少跳帧数，提高精度
            print(f"跳帧数调整为: {skip_frames}")
        elif key == ord('-'):
            skip_frames += 1  # 增加跳帧数，提高速度
            print(f"跳帧数调整为: {skip_frames}")
    
    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()
